<!DOCTYPE html>

<head>
	<meta charset="utf-8">

	<title>Top10_安全事件</title>
	<!--引入d3 -->
	<script src="lib/3D_earth/d3.v3.min.js"></script>
	<!--引入Jquery-->
	<script type="text/javascript" src="lib/jquery-3.1.1.js"></script>
	<!--引入bootstrap文件-->
	<link rel="stylesheet" type="text/css" href="lib/bootstrap-3.3.7/css/bootstrap.min.css">
	<script src="lib/bootstrap-3.3.7/js/bootstrap.min.js"></script>
	<!--引入万能table-->
	<link href="lib/functiontable/datatables.min.css" rel="stylesheet" type="text/css" />
	<link href="lib/functiontable/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
	<!-- END PAGE LEVEL PLUGINS -->
	<!-- BEGIN THEME GLOBAL STYLES -->
	<link href="lib/functiontable/components.min.css" rel="stylesheet" id="style_components" type="text/css" />
	<link href="lib/functiontable/plugins.min.css" rel="stylesheet" type="text/css" />
	<!-- END THEME GLOBAL STYLES -->
	<!-- BEGIN THEME LAYOUT STYLES -->

	<!-- BEGIN PAGE LEVEL PLUGINS -->
	<script src="lib/functiontable/datatables.min.js" type="text/javascript"></script>
	<script src="lib/functiontable/datatables.bootstrap.js" type="text/javascript"></script>
	<!-- END PAGE LEVEL PLUGINS -->
	<!-- BEGIN THEME GLOBAL SCRIPTS -->
	<!--<script src="lib/functiontable/table-datatables-colreorder.min.js" type="text/javascript"></script>-->
	<!-- END PAGE LEVEL SCRIPTS -->
	<!-- BEGIN THEME LAYOUT SCRIPTS -->
	<!--万能表格引入完毕-->

	<style>
		svg {
			font: 12px sans-serif;
		}
		
		text {
			pointer-events: none;
		}
		
		.inner_node rect {
			pointer-events: all;
		}
		
		.inner_node rect.highlight {
			stroke: #315B7E;
			stroke-width: 2px;
		}
		
		.outer_node circle {
			fill: #fff;
			stroke: steelblue;
			stroke-width: 1.5px;
			pointer-events: all;
		}
		
		.outer_node circle.highlight {
			stroke: #315B7E;
			stroke-width: 2px;
		}
		
		.link {
			fill: none;
		}
		
		.basic_back {
			background-color: #404a59;
		}
		
		.svg_legend_rect {
			stroke: #315B7E;
			stroke-width: 3px;
		}
	</style>
</head>

<body class="basic_back">
<!-- 模态框（Modal） -->
	<script>
		$.SHOWMODAL = function() {
			$('#myModal').modal({
				show: true,
				backdrop: true
			});
		};
	</script>
	
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
				<button type="button" class="btn btn-default" style="float: right;" data-dismiss="modal" aria-hidden="true" >
					&times;
				</button>
				
			</div>
				<div class="row">
					<!--
	作者：542440582@qq.com
	时间：2017-01-13
	描述：表格部分
-->
					<div class="col-md-12" id="fair_info" >

						<div class="portlet light bordered ">
							<div class="portlet-title">
								<div class="caption font-dark">
									<i class="icon-settings font-dark"></i>
									<span class="caption-subject bold uppercase" id="fairtitle">TOP10 安全事件</span>
								</div>

							</div>
							<div class="portlet-body">
								<table class="table table-striped table-bordered table-hover" id="fairinfo">

									<thead>
										<tr>
											<th> 事件类型 </th>

											<th>事件发生次数 </th>
											<th> ID </th>
											<th>发生时间</th>
											<th> 事件ID </th>

											<th> 远程IP </th>
											<th> 本地IP </th>
											<th>远程端口</th>
											<th> 本地端口 </th>

											<th> 协议 </th>
											<th> DNS </th>
											<th>远程IP归属</th>
											<th> 本地IP归属 </th>

											<th> 连接方向</th>
											<th> 攻击源背景 </th>

										</tr>
									</thead>
									<tbody>

									</tbody>
								</table>
							</div>
						</div>
					</div>

				</div>
				<div class="modal-footer">

				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal -->
	</div>

	<h1 align="left">TOP10_安全事件</h1>
	<!--
    	作者：542440582@qq.com
    	时间：2017-01-13
    	描述：利用bootstrap的row来控制svg的width属性
    -->
	<div class="col-md-3" style="height: 800px;">
		<!--500px 20% 硬编码，还不知道如何解决-->
		<svg width="400px" height="1000px" id="legend_svg" style="margin-top: 20%;">

		</svg>
	</div>
	<!--style="border: 1px solid;"-->
	<!--	//这里高度设置为1000px是因为后面的画布大小为960*960  -9%硬编码-->

	<div class="col-md-9" style="height: 800px;">
		<svg width="1000px" height="1000px" style="margin-top: -9%;" id="graph_svg">

		</svg>
	</div>

	<!--
    	作者：542440582@qq.com
    	时间：2017-01-13
    	描述：利用D3画关系图和legend部分
    -->

	<script>
		$.ajaxSetup({
			async: false
		});

		$.getTwoDensionArr = function(dension, len) {
			var arr = new Array();
			for(var i = 0; i < dension; i++) {
				arr[i] = new Array();
				for(var j = 0; j < len; j++) {
					arr[i][j] = "dafault";
				}
			}
			return arr;
		};
		//定义table数据的全局变量
		fair_switch_data = $.getTwoDensionArr(0, 15);

		//获取所有的json输入，输入到指定格式的all_fair数组中
		var all_fair = [];
		var input_data = {};
		input_data.starttime = "2017-1-1 00:00:00";
		input_data.endtime="2017-1-17 00:00:00";
		//等待联调 var data = 接口（）；
		$.get('static/data/top10Threat/top10Threat.json', function(data) {

			attack_fair = data.data;
			//			
			//function compare(property){
			//  return function(a,b){
			//      var value1 = a[property];
			//      var value2 = b[property];
			//      return value1 - value2;
			//  }
			//}
			//
			//			console.log(attack_fair.sort(compare('count')));//打印出转化的数据数组
			attack_fair.forEach(function(item, i) {

				var attacker_ip = {};
				var underattacker_ip = {};

				//通过连接方向决定攻击者和被攻击者
				var direction = item.detail[0].ljfx;
				if(direction === 1) {
					attacker_ip.name = item.detail[0].ycip;
					underattacker_ip.name = item.detail[0].bdip;

				} else {
					attacker_ip.name = item.detail[0].bdip;
					underattacker_ip.name = item.detail[0].ycip;
				}

				var one_fair = [];
				var one_atkAndatkd = [];

				one_atkAndatkd.push(underattacker_ip.name, attacker_ip.name);
				one_fair.push(item.sjlx2);
				one_fair.push(one_atkAndatkd);
				one_fair.push(parseInt(item.count));

				if(all_fair.toString().indexOf(item.sjlx2) === -1) {

					all_fair.push(one_fair);
				} else {
					all_fair.forEach(function(item_inner, i_inner) {
						if(item_inner[0] === item.sjlx2) {
							item_inner[1].push(underattacker_ip.name, attacker_ip.name);
							item_inner[2] = parseInt(item_inner[2]) + parseInt(item.count);
						}
					});

				}

			});

		});
		//画关系图部分——转换数据
		var outer = d3.map();
		var inner = [];
		var links = [];
		var outerId = [0];

		all_fair.forEach(function(d) {

			if(d == null)
				return;

			i = {
				id: 'i' + inner.length,
				name: d[0],
				related_links: [],
				count: d[2]
			};
			i.related_nodes = [i.id];
			inner.push(i);

			if(!Array.isArray(d[1]))
				d[1] = [d[1]];

			d[1].forEach(function(d1) {

				o = outer.get(d1);

				if(o == null) {
					o = {
						name: d1,
						id: 'o' + outerId[0],
						related_links: []
					};
					o.related_nodes = [o.id];
					outerId[0] = outerId[0] + 1;

					outer.set(d1, o);
				}

				// create the links
				l = {
					id: 'l-' + i.id + '-' + o.id,
					inner: i,
					outer: o
				}
				links.push(l);

				// and the relationships
				i.related_nodes.push(o.id);
				i.related_links.push(l.id);
				o.related_nodes.push(i.id);
				o.related_links.push(l.id);
			});
		});
		//d3画图需要的数据格式
		console.log(inner);
		data = {
				inner: inner,
				outer: outer.values(),
				links: links
			}
			// sort the data -- TODO: have multiple sort options
		outer = data.outer;
		data.outer = Array(outer.length);
		var i1 = 0;
		var i2 = outer.length - 1;
		for(var i = 0; i < data.outer.length; ++i) {
			if(i % 2 == 1)
				data.outer[i2--] = outer[i];
			else
				data.outer[i1++] = outer[i];
		}
		console.log(data.outer.reduce(function(a, b) {
			return a + b.related_links.length;
		}, 0) / data.outer.length);
		// from d3 colorbrewer: 
		// This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/).
		var colors = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3']
		var color = d3.scale.linear()
			.domain([60, 220])
			.range([colors.length - 1, 0])
			.clamp(true);
		var diameter = 950;
		var rect_width = 100; //调整inode整体矩形大小
		var rect_height = 60;
		var link_width = "1px";
		var il = data.inner.length;
		var ol = data.outer.length;
		var inner_y = d3.scale.linear()
			.domain([0, il])
			.range([-(il * rect_height) / 2, (il * rect_height) / 2]);
		mid = (data.outer.length / 2.0)
		var outer_x = d3.scale.linear()
			.domain([0, mid, mid, data.outer.length])
			.range([15, 170, 190, 355]);
		var outer_y = d3.scale.linear()
			.domain([0, data.outer.length])
			.range([0, diameter / 2 - 120]);
		// setup positioning
		data.outer = data.outer.map(function(d, i) {
			d.x = outer_x(i);
			d.y = diameter / 3;
			return d;
		});
		data.inner = data.inner.map(function(d, i) {
			d.x = -(rect_width / 2);
			d.y = inner_y(i);
			return d;
		});

		function get_color(name) {
			var c = Math.round(color(name));
			if(isNaN(c))
				return '#dddddd'; // fallback color

			return colors[c];
		}
		// Can't just use d3.svg.diagonal because one edge is in normal space, the
		// other edge is in radial space. Since we can't just ask d3 to do projection
		// of a single point, do it ourselves the same way d3 would do it.  
		function projectX(x) {
			return((x - 90) / 180 * Math.PI) - (Math.PI / 2);
		}
		var diagonal = d3.svg.diagonal()
			.source(function(d) {
				return {
					"x": d.outer.y * Math.cos(projectX(d.outer.x)),
					"y": -d.outer.y * Math.sin(projectX(d.outer.x))
				};
			})
			.target(function(d) {
				return {
					"x": d.inner.y + rect_height / 2,
					"y": d.outer.x > 180 ? d.inner.x : d.inner.x + rect_width
				};
			})
			.projection(function(d) {
				return [d.y, d.x];
			});
		//画legend部分，后面看改不改代码，利用css类来控制
		var legend_step = 40;
		var legend_text_start_x = 120;
		var legend_text_start_y = 50;
		var legend_x = 10;
		var legend_y = 40;
		var legend_rx = 20;
		var legend_ry = 20;
		var legend_width = 100;
		var legend_height = 20;
		var svg_legend = d3.select("#legend_svg");
		svg_legend.selectAll("rect")
			.data(inner)
			.enter()
			.append("rect")
			.attr("y", function(d, i) {
				return legend_y + i * legend_step;
			})
			.attr("x", legend_x)
			.attr("rx", legend_rx)
			.attr("ry", legend_ry)
			.attr("width", legend_width)
			.attr("height", legend_height)
			.attr("fill", function(d, i) {
				return get_color(d.count);
			})
			.attr("class", "svg_legend_rect")
			.on("click", legend_rect_click)

		;

		svg_legend.selectAll("text").data(inner).enter().append("text")
			.attr("y", function(d, i) {
				return legend_text_start_y + i * legend_step;
			})
			.attr("x", legend_text_start_x)

		.text(function(d) {
				return d.name + ":" + d.count;
			})
			.style("font-size", "20px");
		//画关系图部分——画图

		var svg_graph = d3.select("#graph_svg")

		.append("g")
			.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");

		// links
		var link = svg_graph.append('g').attr('class', 'links').selectAll(".link")

		.data(data.links)
			.enter().append('path')
			.attr('class', 'link')
			.attr('id', function(d) {
				return d.id
			})
			.attr("d", diagonal)
			.attr('stroke', function(d) {
				return get_color(d.inner.count);
			})
			.attr('stroke-width', link_width);
		// outer nodes
		var onode = svg_graph.append('g').selectAll(".outer_node")
			.data(data.outer)
			.enter().append("g")
			.attr("class", "outer_node")
			.attr("transform", function(d) {
				return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
			})
			.on("mouseover", mouseover)
			.on("mouseout", mouseout);

		onode.append("circle")
			.attr('id', function(d) {
				return d.id
			})
			.attr("r", 4.5);

		onode.append("circle")
			.attr('r', 20)
			.attr('visibility', 'hidden');

		onode.append("text")
			.attr('id', function(d) {
				return d.id + '-txt';
			})
			.attr("dy", ".31em")
			.attr("text-anchor", function(d) {
				return d.x < 180 ? "start" : "end";
			})
			.attr("transform", function(d) {
				return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
			})
			.text(function(d) {
				return d.name;
			});

		// inner nodes

		var inode = svg_graph.append('g').selectAll(".inner_node")
			.data(data.inner)
			.enter().append("g")
			.attr("class", "inner_node")

		.attr("transform", function(d, i) {
			return "translate(" + d.x + "," + d.y + ")"
		})

		.on("mouseover", mouseover)
			.on("mouseout", mouseout)
			.on("click", onclick);

		inode.append('rect')
			.attr('width', rect_width)
			.attr('height', rect_height)
			.attr('id', function(d) {
				return d.id;
			})
			.attr('fill', function(d) {
				return get_color(d.count);
			});

		inode.append("text")
			.attr('id', function(d) {
				return d.id + '-txt';
			})
			.attr('text-anchor', 'middle')
			.attr("transform", "translate(" + rect_width / 2 + ", " + rect_height * .75 + ")")
			.text(function(d) {
				return d.name;
			});
		// need to specify x/y/etc
		d3.select(self.frameElement).style("height", diameter - 150 + "px");

		function legend_rect_click(d) {
			var temp = d.name.split(":");
			var inode_name = temp[0];
			var patt = /事件/g;
			if(patt.test(inode_name)) {
				var all_fit_item = [];
				attack_fair.forEach(function(item, i) {
					if(item.sjlx2 === inode_name) {

						all_fit_item.push(item);
					}

				});
				var table_rows = all_fit_item.length;
				//alert(table_rows);
				fair_switch_data = $.getTwoDensionArr(table_rows, 15);
				var temp = [];
				all_fit_item.forEach(function(item, i) {
					temp.push(item.sjlx2, item.count, item.detail[0].id, item.detail[0].sj, item.detail[0].sjid, item.detail[0].ycip, item.detail[0].bdip, item.detail[0].ycdk, item.detail[0].bddk, item.detail[0].xy, item.detail[0].dns, item.detail[0].ycwz, item.detail[0].bdwz, item.detail[0].ljfx, item.detail[0].gjybj);
					fair_switch_data[i] = temp;
					temp = [];

				});

			}

			$('#fairinfo').dataTable({

				// Or you can use remote translation file
				//"language": {
				//   url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
				//},

				// setup buttons extentension: http://datatables.net/extensions/buttons/
				buttons: [{
					extend: 'print',
					className: 'btn dark btn-outline'
				}, {
					extend: 'pdf',
					className: 'btn green btn-outline'
				}, {
					extend: 'csv',
					className: 'btn purple btn-outline '
				}],

				// setup responsive extension: http://datatables.net/extensions/responsive/
				responsive: true,

				// setup colreorder extension: http://datatables.net/extensions/colreorder/
				colReorder: {
					reorderCallback: function() {
						console.log('callback');
					}
				},

				"order": [
					[0, 'asc']
				],

				"lengthMenu": [
					[5, 10, 15, 20, -1],
					[5, 10, 15, 20, "All"] // change per page values here
				],
				// set the initial value
				"pageLength": 10,
				"destroy": true,
				"data": fair_switch_data,

				"dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable

				// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
				// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). 
				// So when dropdowns used the scrollable div should be removed. 
				//"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
			});
			$.SHOWMODAL();
		};

		function mouseover(d) {
			// bring to front
			d3.selectAll('.links .link').sort(function(a, b) {
				return d.related_links.indexOf(a.id);
			});

			for(var i = 0; i < d.related_nodes.length; i++) {
				d3.select('#' + d.related_nodes[i]).classed('highlight', true);
				d3.select('#' + d.related_nodes[i] + '-txt').attr("font-weight", 'bold');
			}

			for(var i = 0; i < d.related_links.length; i++)
				d3.select('#' + d.related_links[i]).attr('stroke-width', '5px');
		}

		function mouseout(d) {
			for(var i = 0; i < d.related_nodes.length; i++) {
				d3.select('#' + d.related_nodes[i]).classed('highlight', false);
				d3.select('#' + d.related_nodes[i] + '-txt').attr("font-weight", 'normal');
			}

			for(var i = 0; i < d.related_links.length; i++)
				d3.select('#' + d.related_links[i]).attr('stroke-width', link_width);
		}

		function onclick(d) {

		}

		//万能表初始化,获得所有信息
		jQuery(document).ready(function() {
			//attacker是获取的所有json数据
			var all_fit_item = [];
			attack_fair.forEach(function(item, i) {

				all_fit_item.push(item);

			});
			var table_rows = all_fit_item.length;
			//alert(table_rows);
			fair_switch_data = $.getTwoDensionArr(table_rows, 15);
			var temp = [];
			all_fit_item.forEach(function(item, i) {
				temp.push(item.sjlx2, item.count, item.detail[0].id, item.detail[0].sj, item.detail[0].sjid, item.detail[0].ycip, item.detail[0].bdip, item.detail[0].ycdk, item.detail[0].bddk, item.detail[0].xy, item.detail[0].dns, item.detail[0].ycwz, item.detail[0].bdwz, item.detail[0].ljfx, item.detail[0].gjybj);
				fair_switch_data[i] = temp;
				temp = [];

			});
			$('#fairinfo').dataTable({

				// Or you can use remote translation file
				//"language": {
				//   url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
				//},

				// setup buttons extentension: http://datatables.net/extensions/buttons/
				buttons: [{
					extend: 'print',
					className: 'btn dark btn-outline'
				}, {
					extend: 'pdf',
					className: 'btn green btn-outline'
				}, {
					extend: 'csv',
					className: 'btn purple btn-outline '
				}],

				// setup responsive extension: http://datatables.net/extensions/responsive/
				responsive: true,

				// setup colreorder extension: http://datatables.net/extensions/colreorder/
				colReorder: {
					reorderCallback: function() {
						console.log('callback');
					}
				},

				"order": [
					[0, 'asc']
				],

				"lengthMenu": [
					[5, 10, 15, 20, -1],
					[5, 10, 15, 20, "All"] // change per page values here
				],
				// set the initial value
				"pageLength": 10,
				"destroy": true,
				"data": fair_switch_data,

				"dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable

				// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
				// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). 
				// So when dropdowns used the scrollable div should be removed. 
				//"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

			});

		});
	</script>